<?php
/**
 * 订单处理model
 * Created by Forever.
 * User: Forever
 * Date: 2018/10/03 
 * Time: 上午 10:39
 */
namespace app\system\model;
use think\Cache;
use \think\Model;
use \think\db; 
class Order extends Base{

    public function initialize() { }  


    /*
    * 获取我的订单列表
    * @param data
    * @return object
    */
    public function getMyOrderList($data=[]){
        $data['page'] = isset($data['page'])?$data['page']:1;
        $data['rows'] = isset($data['rows'])?$data['rows']:10;
        $where = [];
        if(isset($data['status'])  && !empty($data['status'])){

        }
        $field = "o.id,o.order_no,o.uid,o.member_id,o.title,o.pic,o.unit_price,o.num,o.status,o.total_price,o.paid_price,o.addtime,o.first,o.first_percent,m.name";
        $list['total'] = Db::name(self::$tb['order'])->alias("o")->join("jun_member m","m.id=o.member_id","left")->where($where)->count();
        $list['list'] = Db::name(self::$tb['order'])->alias("o")->join("jun_member m","m.id=o.member_id","left")->where($where)->field($field)->page($data['page'],$data['rows'])->select();
        return $list??[];
    }
    
    /*
    * 获取订单列表
    * @param data
    * @return object
    */
    public function getOrderList($data=[]){
        $data['page'] = isset($data['page'])?$data['page']:1;
        $data['rows'] = isset($data['rows'])?$data['rows']:10;
        $where = [];
        //订单号查询
        if(isset($data['order_no']) && !empty($data['order_no'])){
            $where['o.order_no'] = ["like","%{$data['order_no']}%"];
        }

        //状态类型查询
        if(isset($data['order_type']) && !empty($data['order_type'])){
            if($data['order_type'] == 1){  
              //已完成
              $where['o.status'] = ["in",['1,2']];
            }else{
              $where['o.status'] = ["in",['0,3']];
            }
        }
        //状态查询
        if(isset($data['status']) && !empty($data['status'])){
            $where['o.status'] = $data['status'];
        }
        //经销商查询
        if(isset($data['shop_id']) && !empty($data['shop_id'])){
            $where['o.shop_id'] = $data['shop_id'];
        }

        //按照时间查询
        if(isset($data['start_time']) && !empty($data['start_time'])){
            $where['o.addtime'] = ['between',[$data['start_time'],$data['end_time']]];
        }

        //按照月份查询
        if(isset($data['year']) && !empty($data['year'])){
            $month = mFristAndLast($data['year'],$data['month']);
            $where['o.addtime'] = ['between',[$month['firstday'],$month['lastday']]];
        }

        //按照销售人员查询
        if(isset($data['keyword']) && !empty($data['keyword'])){
            $where['m.name'] =["like","%{$data['keyword']}%"];
        }

        //按照销售人员查询
       if(isset($data['uid']) && !empty($data['uid'])){
            $where['o.uid'] = $data['uid'];
        }
   
         $field = "o.*,m.name as member_name,u.name as cs_name";
         $list['total'] = Db::name(self::$tb['order'])->alias("o")->join("jun_member m","m.id=o.member_id","left")
        ->join("jun_user u","u.id=o.uid","left")->where($where)->count();
        $list['list'] = Db::name(self::$tb['order'])->alias("o")->join("jun_member m","m.id=o.member_id","left")
        ->join("jun_user u","u.id=o.uid","left")->where($where)->field($field)->page($data['page'],$data['rows'])->select();
        if(!empty($list['list'])){
          foreach ($list['list'] as $key => $value) {
            switch ($value['status']) {
              case 0: $list['list'][$key]['status'] = "未付款";break;
              case 1: $list['list'][$key]['status'] = "已付款";break;
              case 2: $list['list'][$key]['status'] = "已完成";break;
              case 3: $list['list'][$key]['status'] = "已退款";break;
              default: break;
            }
            $list['list'][$key]['addtime'] = date("Y-m-d",$value['addtime']);
            $flow = Db::name(self::$tb['money_flow'])->where(['order_id'=>$value['id'],'uid'=>$value['uid']])->field("money,flow")->find();
            $list['list'][$key]['money_flow'] = $flow['money']??0;
            $list['list'][$key]['flow'] = $flow['flow']?$flow['flow']*100:0;
          }
        }
        return $list??[];
    }



   /*
    * 获取订单详情
    * @param data
    * @return object
    */
    public function getOrderDetail($data=[]){
        $data['page'] = isset($data['page'])?$data['page']:1;
        $data['rows'] = isset($data['rows'])?$data['rows']:10;
        $where = ["id"=>$data['id']]; 
        $list=Db::name(self::$tb['order'])->where($where)->field($field)->page($data['page'],$data['rows'])->select();
        if($list){
            return $list;
        }else{
            return false;
        }
    }


     
     /*
    *订单分佣
    * @param order_no
    * @return object
    */
    public function orderFlow($order_no){
       $flow_set =  config("flow_set");
       $order = Db::name(self::$tb['order'])->where("order_no",$order_no)->field("id,member_id,uid,product_id,status,profits")->find();
       if(!$order) return false;
       if($order['status']==0) return false;
       //查询是否有自定义分佣比例
       $isflow = Db::name(self::$tb['user_flow'])->where("user_id",$order['uid'])->find();
       if($isflow){
         $shop_flow = $isflow['shop_flow'];
         $manager_flow = $isflow['manager_flow'];
         $sale_flow = $isflow['sale_flow'];
       }else{
         $profit = Db::name(self::$tb['product'])->where("id",$order['product_id'])->value("profit");
         if($profit){
            $flow = json_decode($profit);
            $shop_flow = $flow[0];
            $manager_flow = $flow[1];
            $sale_flow = $flow[2];
         }else{
            $shop_flow = $flow_set["shop_flow"];
            $manager_flow = $flow_set["manager_flow"];
            $sale_flow = $flow_set["sale_flow"];
         }  
       }
      
      //业务员分佣(20)
       $user = Db::name(self::$tb['user'])->where('id',$order['uid'])->field("id,pid,shop_id")->find();
       $this->flows($order['uid'],$order['profits'],$sale_flow,$order['id']);  
       //业务经理分佣(20)
       $manager_id = $user['pid'];
       $this->flows($manager_id,$order['profits'],$manager_flow,$order['id']);
       //加盟商分佣(60)
       $shop_id = Db::name(self::$tb['user'])->where(['id'=>$manager_id])->value('pid');
       $this->flows($shop_id,$order['profits'],$shop_flow,$order['id']); 
       return true;

    }


    public function flows($user_id, $profits,$flow,$order_id){
        $user = Db::name(self::$tb['user'])->where("id",$user_id)->value("id");
        if(!$user){
            return false;
        }
       Db::startTrans();
      try{
        $flow_money = $profits*$flow;
        $exit =  Db::name(self::$tb['money_flow'])->where(['uid'=>$user_id,'order_id'=>$order_id])->value("id");
        if(!$exit){
            $flow_insert = [
               "uid"=>$user_id,
               "order_id"=>$order_id,
               "profits"=>$profits,
               "money"=>$flow_money,
               "flow"=>$flow,
               "addtime"=>time()
            ];
            Db::name(self::$tb['money_flow'])->insert($flow_insert);
        }
        Db::commit();                                                                                                                                   
        return true;
      } catch (\Exception $e) {
        Db::rollback();
        //throw($e);
        return -10001;
      } 
    }


    

}    